"""
The MIT License (MIT)
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/esp32-ble-beacon_locating
"""
import sys
sys.path.append('libs/ble')
sys.path.append('libs/beacon')

from utime import sleep
from machine import Pin, PWM
import ubluetooth as bt
from utils import Utilities
from drivers.button import Button
from config import Config
from ble.tools import BLETools


forever_loop = True
button = None
led = None

def main():
	global forever_loop, button, led

	is_beacon_mode = Utilities.is_mode_file_exist()

	def button_press_cb(duration):
		print("button pressed over {} ms".format(duration))

		Utilities.create_or_delete_mode_file()
		Utilities.hard_reset()


	led = Pin(Config.LED, Pin.OUT, value=0)
	button = Button(
		pin = Config.BUTTON,
		press_cb = button_press_cb,
		timeout = 3000,
		behavior = Button.BEHAVIOR_HOLD
	)

	ble = bt.BLE()
	uuid = bt.UUID(Config.UUID)

	try:
		if is_beacon_mode:
			# enter beacon mode
			from beacon.client.ibeacon.ibeacon import iBeacon

			led.on()

			major = 10010
			minor = 10086

			tx_power = BLETools.convert_tx_power_level(-50)
			name = "MicroPython iBeacon" # optional

			# payload = BLETools.advertising_ibeacon_payload(uuid, major, minor, tx_power)
			# print("iBeacon payload: [{}]".format(payload))

			beacon = iBeacon(ble, uuid, major, minor, tx_power, name)
			beacon.advertise()
		else:
			# enter scanner mode
			from ble.const import BLEConst
			from beacon.manager.scanner import Scanner
			from beacon.manager.beacon_factory import BeaconFactory

			led.off()

			def scan_result_cb(data):
				addr_type, addr, adv_type, rssi, payload = data
				# (0, b'|\xdf\xa1\xc2\xa3\x0e', 2, -53, b"\x02\x01\x06\x1a\xffL\x00\x02\x15/\xe9T\x96\xf5\xaf\x11\xeb\x9a\x03\x02B\xac\x13\x00\x03'\x1a'f\xc4")

				# BeaconFactory.show(data)
				# [7C:DF:A1:C2:A3:0E], iBeacon: ([2fe95496-f5af-11eb-9a03-0242ac130003], major=10010, minor=10086, tx_power=-60)

				if adv_type == BLEConst.ADVType.ADV_SCAN_IND:
					if BeaconFactory.check(data) == BLEConst.BeaconType.BEACON_IBEACON:
						if BLETools.decode_beacon_data(payload)[1] == Config.UUID:
							factory.append(data)

			factory = BeaconFactory()
			scanner = Scanner(ble, scan_result_cb)

			scanner.scan()
	except KeyboardInterrupt:
		forever_loop = False

		print("\nPRESS CTRL+D TO RESET DEVICE")

		# if led is not None: led.deinit()
		ble.active(False)
		if button: button.deinit()


if __name__ == '__main__':
	main()
